package com.net.web.server;

import com.net.common.util.ThreadPoolFactory;
import com.net.common.util.SnowflakeIdGenerator;
import com.net.web.server.config.ServerConfig;
import com.net.web.server.server.ServerSocketRunnable;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Objects;

/**
 * @author hjh
 */
@SpringBootApplication
@MapperScan("com.net.web.app.webapp.mapper")
@Slf4j
@EnableScheduling
public class WebServerApplication implements ApplicationRunner {
    @Autowired
    private ServerConfig serverConfig;

    public static void main(String[] args) {
        SpringApplication.run(WebServerApplication.class, args);
    }

    @Override
    public void run(ApplicationArguments args) {
        System.out.println("\n" +
                "   _       ________________   _______ _______ _______         _______ _______ \n" +
                "  ( (    /(  ____ \\__   __/  (  ____ (  ____ (  ____ )\\     /(  ____ (  ____ )\n" +
                "  |  \\  ( | (    \\/  ) (     | (    \\/ (    \\/ (    )| )   ( | (    \\/ (    )|\n" +
                "  |   \\ | | (__      | |     | (_____| (__   | (____)| |   | | (__   | (____)|\n" +
                "  | (\\ \\) |  __)     | |     (_____  )  __)  |     __| (   ) )  __)  |     __)\n" +
                "  | | \\   | (        | |           ) | (     | (\\ (   \\ \\_/ /| (     | (\\ (   \n" +
                "  | )  \\  | (____/\\  | |     /\\____) | (____/\\ ) \\ \\__ \\   / | (____/\\ ) \\ \\__\n" +
                "  |/    )_|_______/  )_(     \\_______|_______//   \\__/  \\_/  (_______//   \\__/\n" +
                "                                                                              \n");
        log.info("net 服务端配置加载完毕,正在启动  -----------------------");
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(serverConfig.getNetPort());
            log.info("net 服务端监听端口{}", serverConfig.getNetPort());
            while (true) {
                Socket clientSocket = serverSocket.accept();
                ThreadPoolFactory.execute(new ServerSocketRunnable(clientSocket, SnowflakeIdGenerator.getId()));
            }
        } catch (Exception e) {
            log.error("net 服务器异常退出", e);
        } finally {
            try {
                if (Objects.nonNull(serverSocket)) {
                    serverSocket.close();
                }
            } catch (IOException e) {
                log.error("关闭连接出错", e);
            }
        }
    }
}
